package com.smarthospital.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smarthospital.common.util.IDGeneratorUtil;
import com.smarthospital.dao.daoService.InquiryOrderDaoService;
import com.smarthospital.dao.im.daoService.IMMessageDaoService;
import com.smarthospital.entity.im.IMMessage;
import com.smarthospital.entity.pojo.InquiryOrder;
import com.smarthospital.service.IMMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * create by sym  2021/5/19 19:30.
 */
@Slf4j
@Service
public class IMMessageServiceImpl implements IMMessageService {

    @Autowired
    private IMMessageDaoService imMessageDaoService;

    @Autowired
    private InquiryOrderDaoService orderDaoService;

    /**
     * @param session 连接用户session
     */
    @Override
    public void onOpen(Session session) {

        try {
            session.getBasicRemote().sendText(JSON.toJSONString(IMMessage.TIP_ON_OPEN));
        } catch (IOException e) {
            log.error("websocket IO异常 e {}",e.getMessage(),e);
        }
    }

    /**
     * 接收消息
     * @param sessionPools
     * @param message 发送过来的消息，应该也是json体
     */
    @Override
    public void onMessage(ConcurrentHashMap<String,Session> sessionPools, String message) {
        IMMessage imMessage = JSONObject.parseObject(message, IMMessage.class);
        String orderId = imMessage.getOrderId();
        if (StringUtils.isEmpty(orderId)) {
            log.error("【消息服务】 接收消息  orderId为空！");
            return;
        }
        String immessageId = IDGeneratorUtil.generateImmessageId();
        imMessage.setMessageId(Long.valueOf(immessageId));
        //判断当前订单是否结束
        InquiryOrder order = orderDaoService.queryById(Long.valueOf(orderId));
        int type = imMessage.getType();
        if ((!order.getStatus().equals(1)) && type != 6) { //如果订单为不可发发送消息状态
            String senderId = imMessage.getSenderId();
            Session session = sessionPools.get(senderId);
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(IMMessage.TIP_ORDER_STATUS));
            } catch (IOException e) {
                log.error("【消息服务】 接收消息  io错误！");
            }
        }else { //订单可以发送消息
            //接收方在线
            /**
             * 判断消息类型
             * 1.如果正常类型消息  直接入库发给对方  对方不在线  直接入库
             * 2.如果为修改消息状态的消息  修改相应消息已读状态
             */

            if (8 != type) {
                imMessageDaoService.save(imMessage);
                Session session = sessionPools.get(imMessage.getReceiverId());
                if (null != session) {
                    try {
                        session.getBasicRemote().sendText(JSON.toJSONString(imMessage));
                        //给对方发送成功后，给发送方发送【对方已接收】
                        Session sendSession = sessionPools.get(imMessage.getSenderId());
                        sendSession.getBasicRemote().sendText(JSON.toJSONString(IMMessage.TIP_RECEIVER_RECEIVED));
                    } catch (IOException e) {
                        log.error("【消息服务】 接收消息  io错误！");
                    }
                }
            }else{
                imMessageDaoService.messageschangeToReaded(imMessage);
            }
        }
    }



    @Override
    public Page<IMMessage> list(String orderId, Integer pageSize, Integer pageNum) {
        return imMessageDaoService.getByOrderId(orderId,pageNum,pageSize);
    }

    @Override
    public void deleteAll(){
        imMessageDaoService.deleteAll();
    }

}
